import { defineStore } from "pinia";
import {
  getGroupList,
  addGroup,
  editGroup,
  deleteGroup,
  getGroupChatMsg,
  getUserInfo,
  userLogin,
} from "@/api";
import { nextTick } from "vue";
interface ChatItem {
  id: number;
  name: string;
  isedit: boolean;
}
interface MessageItem {
  id?: number;
  role: "user" | "robot";
  content: string;
}

interface IUserinfo {
  name: string;
  avatar: string;
  username: string;
  ai_vip_day: number;
  ai_free_times: number;
  ai_times: number;
  receive_money: number;
  money: number;
}

export const useChatStore = defineStore("chat", {
  state: () => ({
    // 会话列表
    chatList: [] as ChatItem[],
    userstatus: -1,
    activeIndex: -1,
    activeGroupId: 0,
    // 消息列表
    messageList: Array<MessageItem>(),
    mainloading: true,
    siteloading: true,
    // 是否展示面板
    showcanvas: false,
    sendmessageloading: false,
    mainscrollref: null,
    footerref: null,
    mainscrollheight: 0,
    userinfo: null as IUserinfo,
  }),

  actions: {
    async userLogin(params: any = {}) {
      let res = await userLogin(params);
      if (res.code == 200 || res.code == 1) {
        var data = res.data ?? {};
        var token = data.token;
        window.localStorage.setItem("token", token);
        this.init();
      }
      return res;
    },
    async init() {
      await this.getUserInfo();
      if (this.userstatus === 0) {
        this.mainloading = false;
        this.siteloading = false;
        return;
      }
      // 刷新会话列表
      await this.fetchlist();
      // 切换会话
      await this.changeGroup(0);
      this.initScrollHeight();
    },

    async getUserInfo() {
      let res = await getUserInfo();
      let { code, message, data } = res;
      if (code == 1) {
        let userinfo = data || {};
        this.userinfo = userinfo;
        this.userstatus = 1;
      } else if (code == 401) {
        this.userstatus = 0;
        this.userinfo = null;
      }
    },
    // 获取会话的消息列表
    async getMessageList(index: number) {
      if (!this.chatList[index]) return;
      let { id } = this.chatList[index];
      this.mainloading = true;
      let params = { group_id: id };
      let res = await getGroupChatMsg(params);
      let { code, data, msg } = res;
      if (code == 1 || code == 200) {
        this.messageList = data || [];
      } else {
        this.messageList = [];
      }
      this.mainloading = false;
    },

    initScrollHeight() {
      // 获取底部高度
      let footerHeight = this.footerref?.clientHeight;
      nextTick(() => {
        this.mainscrollheight = "calc(100vh - 90px - " + footerHeight + "px)";
      });
    },

    // 获取左侧会话列表
    async fetchlist() {
      const res = await getGroupList();
      let chatlist;
      if (res.code == 200 || res.code == 1) {
        chatlist = res.data.data as ChatItem[];
      } else {
        chatlist = [];
      }
      let formartlist = chatlist.map((item, index) => {
        item.isedit = false;
        return {
          id: item.id,
          name: item.value,
          isedit: item.isedit,
        };
      });
      this.chatList = formartlist;
      this.siteloading = false;
    },

    async changeGroup(index: number) {
      // 设置会话列表
      this.setGroupIndex(index);
      await this.getMessageList(index);
      this.scrollBottom();
    },

    setGroupIndex(index: number) {
      this.activeIndex = index;
      this.activeGroupId = this.chatList?.[index]?.id;
    },

    // 设置会话列表
    setChatList(chatList: Array<any>) {
      this.chatList = chatList;
    },

    quitEdit() {
      this.chatList.forEach((item: any) => {
        item.edit = false;
      });
    },
    async addGroup(title: string) {
      let params = { name: title };
      let res = await addGroup(params);
      await this.fetchlist();
      return res;
    },

    async editGroup(title: string, group_id: number) {
      let params = { name: title, id: group_id };
      let res = await editGroup(params);
      await this.fetchlist();
      return res;
    },

    async deleteGroup(group_id: number) {
      let params = { id: group_id };
      let res = await deleteGroup(params);
      await this.fetchlist();
      return res;
    },

    togglecanvas() {
      this.showcanvas = !this.showcanvas;
    },

    scrollBottom() {
      if (this.mainscrollref) {
        this.mainscrollref.scrollTop = this.mainscrollref.scrollHeight + 40;
      }
      nextTick(() => {
        if (this.mainscrollref) {
          this.mainscrollref.scrollTop = this.mainscrollref.scrollHeight + 40;
        }
      });
    },

    async getAnswer(message: string = "") {
      let activeGroupId = this.activeGroupId;
      if (!activeGroupId) return;
      var token = window.localStorage.getItem("token");
      if (!token) {
        token = window.localStorage.getItem("api_token");
      }

      if (process.env.NODE_ENV !== "production") {
        token =
          "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiOTlmYTU0YjEzNGM1ZDA2YzBkMzcwNTcxOGNhMDA5NTc5ZWJhZTY0NWQ3Y2E0ZjBlZDA5NTU4NTJjZGRkYTZjZDA0YmQyMDkzYTQxMmJmZjQiLCJpYXQiOjE3MDQ5NTQ3NzIsIm5iZiI6MTcwNDk1NDc3MiwiZXhwIjoxNzM2NTc3MTcyLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.Cyj1Az0IpEWs2X1XxJ7_6mCua_rMV6Wrv-CDMHmGg37fQvYvNXjULYvJTsfE6L-IAZQV3ZY35ovZY5_YbIaQrlg6h0D0PCG9VqAQj2f5Her3c5Y4n17aUTG89p39cTRJ5J9HCGAebPmcdY-kbbzirWx_H-sa1Pdd06j0KzTByBv8bz3cjLjFpEI7Aa22r4kK_XhCfgCkMWKuWBAgICnN58rBDXgY-QfoNUI5tLckim8_oSQALywiLMs3xWBOvOxUPe8JD--DOBrny9f2vicf_GSBgDTsk3C8ti4sKb_Msngn129WGZA2hqA77jG0gbuxm2ZFok258qMytxvawGze50_CLuaG9mdDLrCHPaIgYBQX4kpPVFXVbIGvZ-XKtsWiN8_3NqG5y4NgR_a9aoLt2VIbQdD4f7TxZYYYpGv0c1scYTMcxmn31QfjNqLy8qY_y4EbHGaToJ69xu9wmDLci-bdiA5xywFSf1sKpjQFRFd5X1yIhHyEEtCqAIjnXKhVbf8EYGMJJAs1vvGlgxVHhwbFHXdGhKgPSqREEinSasq7wQp6LupMsQq3MhmnLU99pQjKu34loAUdEJ7N1GKNkIPDceW8TsMVFTQ-pAqacfrvjwQfOtBCjpo_RHQCanWaLgOBbGWZMEEkpY6le9ZuSFrd-02nLNOz2bWu-PZTVk4";
      }
      let url =
        import.meta.env.VITE_API_URL +
        "/api/chat/sendtext?message=" +
        message +
        "&token=" +
        token;
      if (activeGroupId) {
        url = url + "&group_id=" + activeGroupId;
      }
      this.messageList.push({
        content: "",
        role: "robot",
      });
      let source = new EventSource(url, {
        type: "text/html",
        headers: {
          accept:
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        },
      });
      source.onopen = (e) => {
        console.log("连接已经建立：", e);
      };
      let index = 0;
      let response = "";
      let timers = null;
      source.onmessage = (event) => {
        var data = event.data || "";
        try {
          data = JSON.parse(data);
          var { code, data, msg } = data;
          if (code == 1 || code == 200) {
            data = data.text.replace(/<br\s*\/?>/g, "\n");
            const content =
              this.messageList[this.messageList.length - 1].content;
            response += data;
            clearInterval(timers);
            timers = setInterval(() => {
              if (index < response.length) {
                this.messageList[this.messageList.length - 1].content =
                  content + response.slice(0, index++);
              } else {
                clearInterval(timers);
                timers = null;
                this.messageList[this.messageList.length - 1].content =
                  content + response;
                this.sendmessageloading = false;
              }
              this.scrollBottom();
            }, 100);
          } else if (code == 401) {
            this.userstatus = 0;
            this.sendmessageloading = false;
          } else {
            ElMessageBox({
              title: "提示",
              message: msg,
              confirmButtonText: "确认",
              callback: function () {
                if (code == 409) {
                  window.location.href = "/order/money?productType=3";
                }
              },
            });
            this.sendmessageloading = false;
          }
        } catch (err) {
          console.log(err);
        }
      };

      source.onerror = async (err) => {
        source.close();
        source = false;
        if (timers == null) {
          this.sendmessageloading = false;
        }
        // 获取用户信息
        await this.getUserInfo();
      };
    },

    async sendMessage(value) {
      this.sendmessageloading = true;
      this.messageList.push({
        content: value,
        role: "user",
      });
      this.scrollBottom();
      this.getAnswer(value);
    },
  },
});
